<?php
class MyPDO {

    private $db = null;
    private $ob = null;
	private $error = array();
    private $debug = 0;	  //打开sql debug
    private $debug_stop = 0;	//是否中止sql
	private $lastid ;	//最后新增id
    private $dbname = null;

    function __construct($dbhost, $dbuser, $dbpass, $dbname, $dbtype = 'mysql', $charset = 'UTF8', $dbport = '3306') {
	if ($dbtype == 'mysql') {
	    try {
		$this->db = new PDO($dbtype . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
	    } catch (PDOException $e) {
		die($e->getMessage());
	    }
	    $this->dbname = $dbname;
	    $this->db->exec("SET NAMES 'utf8';");
	} elseif ($dbtype == 'oracle') {
	    //php_pdo_oci.dll  windows/oci.dll
	    try {
		$this->db = new PDO('oci:dbname=' . $dbname, $dbuser, $dbpass);
		//$dbh = new PDO("OCI:dbname=accounts;charset=UTF8", "username", "password");
	    } catch (PDOException $e) {
		die($e->getMessage());
	    }
	    //putenv("NLS_LANG=simplified chinese_china.zhs16gbk");   //防止乱码
	}

	if (!$this->db) {
	    die("Can not connect the database!");
	}
	$this->db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
    }

    function __destruct() {
	//unset($this->db);
    }

    //取一条记录,一维
    function getRow($sql, $type = PDO::FETCH_ASSOC) {
	$this->checkDebug($sql);
	$this->ob = $this->db->prepare($sql);
	$this->ob->execute();
	if ($this->ob)
	    $rs = $this->ob->fetch($type);
	return $rs;
    }

    //取所有记录,二维
    function getAll($sql, $type = PDO::FETCH_ASSOC) {
	//die($sql);
	$this->checkDebug($sql);
	$this->ob = $this->db->prepare($sql);
	$this->ob->execute();
	if ($this->ob)
	    $rs = $this->ob->fetchAll($type);
	return $rs;
    }

    //取一个字段值
    function getOne($sql) {
	$this->checkDebug($sql);
	$this->ob = $this->db->prepare($sql);
	$this->ob->execute();
	if ($this->ob)
	    $rs = $this->ob->fetchColumn();
	return $rs;
    }

    //添加记录返回最后的插入自增主键,oracle无效
    function getInsertId() {
	return $this->lastid;
    }

	function error() {
		return $this->error;
    }
    //操作执行insert update delete,返回影响条数
	function execute($sql) {
	$rs = $this->db->exec($sql);
	return $rs > 0 ? $rs : false;
    }

    function insert($table, $data) {
	if (!is_array($data) || !$table) {
	    die("参数有误");
	}
	$field = '';
	$value = '';
	foreach ($data as $k => $v) {
	    $field .= '`' . $k . '`,';
	    $value .= '"' . $this->inputSQL($v) . '",';
	}
	$field = rtrim($field, ',');
	$value = rtrim($value, ',');
	$sql = "INSERT INTO `" . $table . "` (" . $field . ") VALUES(" . $value . ")";
	//die($sql);
	$this->checkDebug($sql);
	$rs = $this->db->exec($sql);
	if($this->db->errorCode()=='00000'){
		$this->lastid = $this->db->lastInsertId();
	}else{
		$errors = $this->error;
		$errors[] = $this->db->errorInfo();
		$this->error = $errors;
		//$this->error =array_merge($this->error,$this->db->errorInfo());
		$this->lastid = '';
	}
		return intval($rs);
    }

    function update($table, $data, $where) {
	if (!is_array($data) || !$table || !$where) {
	    die("参数有误");
	}
	$list = '';
	foreach ($data as $k => $v) {
	    if (strstr($v, $k)) {
		$list .= '`' . $k . '` = ' . $v . ',';      //处理增量方式
	    } else {
		$list .= '`' . $k . '` = "' . $this->inputSQL($v) . '" ,';
	    }
	}
	$list = rtrim($list, ',');
	$sql = "UPDATE `" . $table . "` SET " . $list . " WHERE " . $where;
	//die($sql);
	$this->checkDebug($sql);
	$rs = $this->db->exec($sql);
	if($this->db->errorCode()!='00000'){
		$errors = $this->error;
		$errors[] = $this->db->errorInfo();
		$this->error = $errors;
		$rs='0';
	}
	return intval($rs);
    }

    function delete($table, $where) {
	if (!$table) {
	    die("参数有误");
	}
	$sql = "DELETE FROM `" . $table . "` WHERE " . $where;
	//die($sql);
	$this->checkDebug($sql);
	$rs = $this->db->exec($sql);
	if($this->db->errorCode()!='00000'){
		$errors = $this->error;
		$errors[] = $this->db->errorInfo();
		$this->error = $errors;
		$rs='0';

	}
	return intval($rs);
    }

    private function getField($table) {
		$sql = "SELECT COLUMN_NAME,COLUMN_TYPE FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA`='" . $this->dbname . "' AND `TABLE_NAME`='" . $table . "'";
		return $this->getAll($sql);
    }

    //数据库表与表单值映射,获取更新数据值
    public function getFormData($table, $post) {
		$fields = $this->getField($table);
		
		$data = array();
		if ($fields) {
			foreach ($fields as $v) {
			$filed = $v['COLUMN_NAME'];
			if (isset($post[$filed]) && !is_array($post[$filed])) {   //数组值不处理
				$data[$filed] = $this->formatType($v['COLUMN_TYPE'],$post[$filed]);
			}
			}
		}
		return $data;
    }

	//字段映影处理
	private function formatType($type,$value){
		if($type=='date'){
			return $value ? $value : '0000-00-00';
		}elseif($type=='datetime'){
			return $value ? $value : '0000-00-00 00:00:00';
		}elseif(strstr($type,'decimal')){
			return $value ? floatval($value) : '0';
		}elseif(strstr($type,'int')){
			return intval($value);	
		}else{
			return trim($value);
		}
	}

    //检查输出sql
    function checkDebug($sql) {
	if ($this->debug) {
	    echo $sql . '<br />';
	}
	if ($this->debug_stop) {
	    exit;
	}
    }

    //设定是否debug SQL语句
    function debug($type = 1, $stop = 0) {
	$this->debug = intval($type);
	if (intval($stop)) {
	    $this->debug_stop = 1;
	}
    }

    function inputSQL($sql) {
		//return $sql;
		if (!ini_get("magic_quotes_runtime")) {
			return addslashes($sql);
		} else {
			return $sql;
		}
    }

    function outputSQL($sql) {
	if (!ini_get("magic_quotes_runtime")) {
	    return stripslashes($sql);
	} else {
	    return $sql;
	}
    }

    //事务处理开始
    function begin() {
	$this->db->beginTransaction();
    }

    //事务返回
    function back() {
	$this->db->rollBack();
    }

    //事务执行
    function commit() {
	$this->db->commit();
    }

}

/* header('Content-type: text/html; charset=utf-8'); 

  //example
  define("DBHOST","localhost");
  define("DBPORT","3306");
  define("DBUSER","root");
  define("DBPASS","111111");
  define("DBNAME","shoumedia");
  define("DBTYPE","mysql");
  $db = new MyPDO(DBHOST,DBUSER,DBPASS,DBNAME);
  $post = array('admin_name'=>'name','test'=>'','admin_pwd'=>'a');
  echo "<pre>";
  print_r($db->getFormData('sys_admin',$post));
  echo "</pre>";
  $db->debug(1);
  $title = $db->inputSQL("admin");

  $data = $db->getRow("select * from sys_admin where admin_name='".$title."'");
  $data1 = $db->getAll("select * from sys_admin");
  $data2 = $db->getOne("select * from sys_admin");

  $indata['admin_true_name'] = 'adminyaobb';
  $indata['admin_name'] = "alancc";


  $db->begin();
  $rs =$db->insert('sys_admin',$indata);
  if($rs){
  $indata['admin_name'] = "aasdfas";
  $indata['admin_pwd'] = "abc";
  $rs =$db->insert('sys_admin',$indata);
  if($rs){
  $db->commit();
  echo "yyy";
  }else{
  $db->back();
  echo "nnn";
  }

  }


  echo "<pre>";
  print_r($data);
  print_r($data1);
  print_r($data2);
  echo "</pre>"; */
?>